package com.gitee.hermer.engine.jars.dependent.activemq.core;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.gitee.hermer.engine.jars.dependent.activemq.config.ActiveMQProperties;
import com.gitee.hermer.engine.jars.dependent.activemq.core.pool.ActiveMQSessionPoolFactory;

public class ActiveMQCluster implements InitializingBean{

	private String[] brokers;

	private List<ActiveMQSessionPoolFactory> factory = new ArrayList(1);

	private AtomicBoolean isInited = new AtomicBoolean(false);
	
	@Autowired
	private ActiveMQProperties properties;

	@Override
	public void afterPropertiesSet() throws Exception {
		if(isInited.compareAndSet(false, true)){
			String weight = null;
			for (String brokerURL : brokers)
			{
				if (brokerURL.contains("weight="))
				{
					weight = this.getWeight(brokerURL);
					brokerURL = this.getMQBrokerURL(brokerURL);
				}
				factory.add(new ActiveMQSessionPoolFactory(properties,brokerURL, weight).init());
			}
		}
	}



	public List<ActiveMQSessionPoolFactory> getFactory() {
		return factory;
	}



	public ActiveMQCluster(String[] brokers){
		this.brokers = brokers;
	}

	public String getWeight(String brokerURL)
	{
		int index = brokerURL.indexOf("weight=");
		String weigthsalue = brokerURL.substring(index);
		int lastSIndex = weigthsalue.indexOf("&");
		String value = null;
		if (lastSIndex != -1) {
			value = weigthsalue.substring(weigthsalue.indexOf("weight="), 
					lastSIndex);
		} else {
			value = weigthsalue.substring(weigthsalue.indexOf("weight="));
		}
		return value.split("=")[1];
	}

	public String getMQBrokerURL(String brokerURL)
	{
		int index = brokerURL.indexOf("weight=");
		String weigthsalue = brokerURL.substring(index);
		int lastSIndex = weigthsalue.indexOf("&");
		String value = null;
		if (lastSIndex != -1) {
			value = weigthsalue.substring(weigthsalue.indexOf("weight="), 
					lastSIndex);
		} else {
			value = weigthsalue.substring(weigthsalue.indexOf("weight="));
		}
		String qiSvalue = brokerURL.substring(index - 1, index);
		if (!"&".equals(qiSvalue)) {
			value = value + "&";
		} else {
			value = "&" + value;
		}
		return brokerURL.replace(value, "");
	}



}
